package com.grades.springboot.service.impl;

import com.grades.springboot.entity.Result;

import com.grades.springboot.entity.User;
import com.grades.springboot.mapper.AdminMapper;
import com.grades.springboot.mapper.TeacherMapper;
import com.grades.springboot.service.FindPsdService;
import com.grades.springboot.util.Encrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

@Service
public class FindPsdServiceImpl implements FindPsdService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private TeacherMapper teacherMapper;
    @Autowired
    private PermissionVerificationServiceImpl permissionVerificationService;
    @Autowired
    private ValidationServiceImpl validationService;

    @Override
    public Result<?> findPsd(String email, String code, String newPsd, String rePassword, HttpServletRequest request) {
        User user;
        Boolean flag = permissionVerificationService.permissionVerification(request);
        if (flag){
            user = adminMapper.selectByEmail(email);
        }else{
            user = teacherMapper.selectByEmail(email);
        }
        if (user == null){
            return Result.error("此邮箱暂未注册任何账号");
        }else if (!newPsd.equals(rePassword)){
            return Result.error("两次输入的密码不同");
        }else if (!validationService.checkValidation(email, Encrypt.toMD5(code))){
            return Result.error("验证码错误或已过期，请重新获取");
        }
        int count ;
        if (flag){
            count = adminMapper.updatePassword(email,Encrypt.toMD5(newPsd));
        }else{
            count = teacherMapper.updatePassword(email,Encrypt.toMD5(newPsd));
        }
        if (count > 0){
            return Result.success();
        }else{
            return Result.error("更新密码时发生了一个未知错误");
        }
    }
}
